package cn.ithers.blog.controller.user;

import cn.ithers.blog.dto.InitUserDTO;
import cn.ithers.blog.dto.LoginUserDTO;
import cn.ithers.blog.dto.RegisterUserDTO;
import cn.ithers.blog.dto.UpdatePasswordUserDTO;
import cn.ithers.blog.response.ResponseResult;
import cn.ithers.blog.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: zhanghuan
 * @date: 2020/11/11 20:13
 * @description:
 */

@Slf4j
@Api(value = "用户", tags = "用户")
@RestController
@RequestMapping("/user")
public class LoginApi {

    @Autowired
    private IUserService userService;


    /**
     * 初始化管理员账号
     *
     * @return
     */
    @ApiOperation("初始化管理员账号")
    @PostMapping("/admin")
    public ResponseResult initManagerAccount(@RequestBody InitUserDTO initUserDTO, HttpServletRequest request) {

        log.info("username--->" + initUserDTO.getUserName());
        log.info("password--->" + initUserDTO.getPassword());
        log.info("email--->" + initUserDTO.getEmail());
        return userService.initManagerAccount(initUserDTO, request);
    }


    /**
     * 注册
     *
     * @param registerUserDTO
     * @return
     */
    @ApiOperation(value = "注册")
    @PostMapping("sign_up")
    public ResponseResult register(@RequestBody RegisterUserDTO registerUserDTO,
                                   @ApiParam(value = "邮箱验证码", required = true) @RequestParam("email_code") String emailCode,
                                   @ApiParam(value = "人类验证码", required = true) @RequestParam("captcha_code") String captchaCode,
                                   @ApiParam(value = "与获取验证码时输入的保持一致,默认值为：13245864234073", required = true) @RequestParam("captcha_key") String captchaKey,
                                   HttpServletRequest request) {
        return userService.register(registerUserDTO, emailCode, captchaCode, captchaKey, request);
    }
    /**
     * 登录
     * 需要提交的数据
     * 1.用户账号-可以呢称，可以有效---。做了唯一处理
     * 2.密码
     * 3.图灵验证码
     * 4.图灵验证码的keY
     *
     * @param captchaKey
     * @param captcha
     * @param loginUserDTO
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping("/sign_in/{captcha}/{captcha_key}")
    public ResponseResult login(
            @ApiParam(value = "与获取验证码时输入的保持一致,默认值为：13245864234073", required = true) @PathVariable("captcha_key") String captchaKey,
            @ApiParam(value = "人类验证码", required = true) @PathVariable("captcha") String captcha,
            @ApiParam(value = "客户端来源") @RequestParam(value = "from", required = false) String from,
            @RequestBody LoginUserDTO loginUserDTO) {
        return userService.doLogin(captcha, captchaKey, loginUserDTO, from);
    }


    /**
     * 获取图灵验证码
     * 有效时长1分钟
     * captcha_key 长度至少14
     *
     * @return
     */
    @ApiOperation(value = "获取人类验证码")
    @GetMapping("/captcha")
    public void getCaptcha(HttpServletResponse response,
                           @ApiParam(value = "验证码key输入任意一个14位数,默认值为：13245864234073", required = true) @RequestParam("captcha_key") String captchaKey) {

        try {
            userService.createCaptcha(response, captchaKey);
        } catch (Exception e) {
            log.error(e.toString());
        }

    }

    /**
     * 发送邮件
     * 使用场景：注册，找回密码、修改邮箱（输入新邮箱）
     * 注册(register)；如果已经注册过了，提示改邮箱已经注册过了
     * 找回密码(forget)：如果没有注册过，提示改邮箱没有注册
     * 修改邮箱(update)：如果已经注册了，提示改邮箱已经注册过了
     *
     * @param emailAddress
     * @return
     */
    @ApiOperation(value = "发送邮件验证码")
    @GetMapping("/verify_code")
    public ResponseResult sendVerifyCode(HttpServletRequest request,
                                         @ApiParam(value = "type可以取register，forget，update", required = true) @RequestParam(value = "type") String type,
                                         @ApiParam(value = "邮箱地址", required = true) @RequestParam("email") String emailAddress) throws MessagingException {

        log.info("email -->" + emailAddress);
        return userService.sendEmail(type, request, emailAddress);
    }

    /**
     * 修改密码
     * 修改密码
     * 普通做法，通过旧密码对比来更新密码
     * <p>
     * 既可找回密码，又能修改密码
     * 发送验证码到邮箱/手机--->判断验证码是否确定来判断
     * 对应的邮箱/手机号码所注册的账号是否属于你
     * 注册(register)；如果已经注册过了，提示改邮箱已经注册过了
     * 找回密码(forget)：如果没有注册过，提示改邮箱没有注册
     * 修改邮箱(update)：如果已经注册了，提示改邮箱已经注册过了
     * 步骤
     * 1.用户填写邮箱
     * 2.用户获取验证码type=forget
     * 3.填写验证码
     * 4填写新密码
     * 5.提交数据
     * 数据包括
     * 1.邮箱和密码
     * 2.验证码
     * 3.如果验证码正确--》所用邮箱的账号是你的，可以修改密码
     *
     * @param verifyCode
     * @param updatePasswordUserDTO
     * @return
     */
    @ApiOperation(value = "修改密码", notes = "verfyCode: 邮箱验证码")
    @PutMapping("/password/{verifyCode}")
    public ResponseResult updatePassword(@ApiParam(value = "邮箱验证码", required = true) @PathVariable("verifyCode") String verifyCode,
                                         @RequestBody UpdatePasswordUserDTO updatePasswordUserDTO) {
        return userService.updateUserPassword(verifyCode, updatePasswordUserDTO);
    }
    /**
     * 退出登录
     * 1.拿到tokenkey
     * 2.删除redis里对应的token
     * 删除mysql里的refreshtoken
     * 删除cookie里的token_key
     *
     * @return
     */
    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public ResponseResult logout() {
        return userService.doLogOut();
    }
}
